package com.itcast.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itcast.common.BaseController;
import com.itcast.entity.User;
import com.itcast.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api")
public class AjaxUserController extends BaseController {

    @Autowired
    private UserService userService;

    // 分页查询接口 http://localhost:8100/api/users?pageNum=1&pageSize=5
    @GetMapping("/users")
    public ResponseEntity<Map<String, Object>> getUsers(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize) {

        // 1. 初始化分页
        PageHelper.startPage(pageNum, pageSize);

        // 2. 查询数据
        List<User> users = userService.selectAllUsers();
        PageInfo<User> pageInfo = new PageInfo<>(users);

        // 3. 构建响应体 (JDK8兼容写法)
        Map<String, Object> response = new LinkedHashMap<>();
        response.put("code", 200);
        response.put("success", true);
        response.put("data", pageInfo.getList());
        response.put("total", pageInfo.getTotal());
        response.put("pages", pageInfo.getPages());
        response.put("currentPage", pageInfo.getPageNum());
        response.put("pageSize", pageInfo.getPageSize());

        // 4. 添加分页导航信息
        Map<String, Integer> navigation = new HashMap<>();
        navigation.put("firstPage", 1);
        navigation.put("prePage", pageInfo.getPrePage());
        navigation.put("nextPage", pageInfo.getNextPage());
        navigation.put("lastPage", pageInfo.getPages());
        response.put("navigation", navigation);

        return ResponseEntity.ok(response);

    }
}